﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using NanoERP.Model;
using NanoERP.Common;
using NanoERP.Business.BaseInfo;
using DevComponents.AdvTree;
using System.Text.RegularExpressions;

namespace NanoERP.BaseInfo
{
    //[Module("FrmDicData")]
    public partial class FrmDicData : Form
    {
        readonly SysdictableBLL _sysdictablebLl;
        /// <summary>
        /// 是否多级添加，默认：false
        /// </summary>
        readonly bool _isMulti;
        /// <summary>
        /// 是否选择根节点
        /// </summary>
        readonly bool _isSelectRoot;
        public FrmDicData()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 数据字典维护
        /// </summary>
        /// <param name="id">类别ID</param>
        /// <param name="isMulti">是否多级添加，默认：false</param>
        /// <param name="isQuery">是否查询，默认：false</param>
        /// <param name="isSelectRoot">是否选择根节点，默认：true</param>
        public FrmDicData(int id, bool isMulti = false, bool isQuery = false, bool isSelectRoot = true)
        {
            InitializeComponent();
            _sysdictablebLl = new SysdictableBLL();
            _isMulti = isMulti;
            _isSelectRoot = isSelectRoot;
            txtKey.Visible = tsbSelect.Visible = tSeparator1.Visible = isQuery;

            BindTreeView(id);
        }

        /// <summary>
        /// 绑定字典树
        /// </summary>
        /// <param name="id"></param>
        void BindTreeView(int id)
        {
            dicTree.Nodes.Clear();

            var sysdic = _sysdictablebLl.Get(id);
            var firNode = new Node(sysdic.Dicname) { Tag = sysdic, Name = sysdic.Id.ToString(), Image = NanoERP.Properties.Resources.XmlStructure };
            firNode.ExpandAll();
            var firList = _sysdictablebLl.Query(sysdic.Id);
            RecursiveLoopNodes(firList, firNode);

            dicTree.Nodes.Add(firNode);
            if (dicTree.Nodes.Count > 0) dicTree.SelectedNode = dicTree.Nodes[0];
        }

        /// <summary>
        /// 刷新字典树
        /// </summary>
        /// <param name="selectedNode"></param>
        void RefreshTree(Node selectedNode)
        {
            selectedNode.Nodes.Clear();
            var id = int.Parse(selectedNode.Name);
            RecursiveLoopNodes(_sysdictablebLl.Query(id), selectedNode);
        }

        /// <summary>
        /// 递归循环调用
        /// </summary>
        /// <param name="firList">一级树集合</param>
        /// <param name="parentNode">上级节点</param>
        void RecursiveLoopNodes(List<Sysdictable> firList, Node parentNode)
        {
            firList.ForEach(r =>
            {
                var secNode = new Node(r.Dicname) { Tag = r, Name = r.Id.ToString(), Image = NanoERP.Properties.Resources.CreateTableTemplatesGallery };

                parentNode.Nodes.Add(secNode);
                var recList = _sysdictablebLl.Query(r.Id).ToList();
                if (recList.Count > 0)
                    RecursiveLoopNodes(recList, secNode);
            });
        }

        private void tsbAdd_Click(object sender, EventArgs e)
        {
            var node = _isMulti ? dicTree.SelectedNode : dicTree.Nodes[0];
            var sysDic = node.Tag as Sysdictable;
            var sysdictable = new Sysdictable { Parent = sysDic.Id };
            var f = new FrmDicDataEdit(sysdictable, sysDic.Dicname);
            if (f.ShowDialog() == DialogResult.OK)
            {
                RefreshTree(node);
            }
        }

        private void tsbEdit_Click(object sender, EventArgs e)
        {
            var node = _isMulti ? dicTree.SelectedNode.Parent : dicTree.Nodes[0];
            var sysDic = dicTree.SelectedNode.Tag as Sysdictable;
            if (sysDic == null) return;
            var f = new FrmDicDataEdit(sysDic, dicTree.SelectedNode.Text);
            if (f.ShowDialog() == DialogResult.OK)
            {
                RefreshTree(node);
            }
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            Node node = dicTree.SelectedNode;
            var v = (Sysdictable)node.Tag;
            string text;
            if (dicTree.SelectedNode.LastNode != null)
            {
                text = string.Format(@"请先“删除”该节点“{0}”下级数据.", v.Dicname);
                MessageBox.Show(text, @"提示消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            text = string.Format(@"您要确定要“删除”数据“{0}”吗？", v.Dicname);
            if (MessageBox.Show(text, @"请确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                _sysdictablebLl.Delete(v);
                RefreshTree(node.Parent);
            }
        }

        private IEnumerable<Node> _treeNodes;
        private int _nodeIndex;
        private void tsbSelect_Click(object sender, EventArgs e)
        {
            if (_treeNodes == null || !_treeNodes.Any()) return;
            dicTree.SelectedNode = _treeNodes.ToArray()[_nodeIndex];
            _nodeIndex = (_nodeIndex < _treeNodes.Count() - 1) ? ++_nodeIndex : 0;
        }

        private void tsbExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dicTree_NodeDoubleClick(object sender, TreeNodeMouseEventArgs e)
        {
            if (e.Node.Level == 0 && !_isSelectRoot)
                return;
            this.Tag = e.Node.Tag as Sysdictable;
            this.DialogResult = DialogResult.OK;
        }

        private void txtKey_TextChanged(object sender, EventArgs e)
        {
            _nodeIndex = 0;
            if (_nodeIndex == 0)
                _treeNodes = dicTree.Nodes.TreeWhere(t => Regex.IsMatch(t.Text, @"(?i)" + txtKey.Text));
        }

        private void dicTree_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e)
        {
            tsbEdit.Enabled = tsbDelete.Enabled = !e.Node.Level.Equals(0);
        }
    }
}
